package com.yenlien.traceyun.control.interceptor;

import com.yenlien.traceyun.common.crypt.TokenUtil;
import com.yenlien.traceyun.webase.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: bigwangy@sina.com
 * @create: 2020-03-09
 * @description:
 **/
public class TokenInterceptor implements HandlerInterceptor {


    private String[] exceptUrls = {"/cms/**", "/model/**", "/user/checkCode", "/user/logins", "/re/**", "/scan/**", "/plant/scan/**", "/breed/traceinfo/**", "/traceinfo/**", "/companyshow/**", "/", "/error", "/management/**", "/template/**", "/user/login/**", "/file/**", "/error/**", "/file/qiniu/**", "/index.html", "/dist/**", "/static/**", "/css/**", "/fonts/**", "/js/**"};
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws BusinessException {
        //通过地址集拦截
        String url = request.getRequestURI();

//        for (String item : exceptUrls) {
//            if (url.startsWith(item)) {
//                return true;
//            }
//        }
        for (String item : exceptUrls) {
            if (antPathMatcher.match(item, url)) {
                return true;
            }
        }


        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new BusinessException("500", "未登录");
        }
        TokenUtil.veryToken(token, "123456");
        return true;
    }
}
